//License: Artistic License v2.0, http://opensource.org/licenses/Artistic-2.0

package main

import (
	"log"
	"net"
	"net/http"
)

//userPasswordIsOk checks the password stored in the named user file.
//One user one file.
func userPasswordIsOk(userId, password string) bool {
	var user struct { //struct of the user.json file for each user
		PasswordKey  string
		PasswordHash []byte
	}
	err := Json("get", path("user")+userId+".json", &user)
	if err != nil {
		log.Println(projName, err)
		return false
	}
	return EncodingIsOk(password, user.PasswordKey, user.PasswordHash)
}

//listenToUpdate listens to message from authorised user to update / reload / refresh
//all contents from disk to memory.  Err checks below are needed, not redundant,
//for security measure in case the conn / listener is exposed.
func listenToUpdate(listener *net.Listener) {
	var msg []string
	for {
		msg = GetMsg(listener)
		cmd, user, password := msg[0], msg[1], msg[2]
		if cmd != "update" {
			log.Println(projName, "Received and ignored msg:", cmd)
			return
		}
		if password != "" && user != "" && userPasswordIsOk(user, password) {
			log.Println(projName, "Received update request from", user)
			updateAll()
		} else {
			log.Println(projName, "Received update request with invalid auth:", user)
		}
	}
}

func updateAll() {
	var found bool
	if err := readDataFiles(); err == nil {
		newStaticContents := loadStaticContents()
		for urlPath, _ := range newStaticContents {
			if _, found = staticContents[urlPath]; found == false { //not found
				//new static file, so we need to register it
				http.HandleFunc(urlPath, getStatic)
			}
		}
		//When "static content" is removed, the gz is emptied, but the urlPath is not deregistered
		//bec there is no standard http func to deregister a path from http.HandleFunc
		//There should be no issue with removed "copy" since it is handled by getPage
		staticContents = newStaticContents
		htmlContents = loadAssembledContents(&copies)
	} else {
		log.Println(projName, "update:", err)
	}
}

//Copyright: Slamet Hendry
